# uncompyle6 version 3.2.3
# Python bytecode 3.6 (3379)
# Decompiled from: Python 3.6.8 |Anaconda custom (64-bit)| (default, Feb 21 2019, 18:30:04) [MSC v.1916 64 bit (AMD64)]
# Embedded file name: server\http_responses\file_download.py
__author__ = "sanyi"
import mimetypes
from os.path import isfile
from server.http_responses.base import BaseResponse


class FileDownload(BaseResponse):
    def __init__(
        self,
        file_path,
        headers=None,
        response_status="200 OK",
        cookie=None,
        mime_type=None,
        fallback_mime_type="text/plain",
        chunk_length=65536,
        open_file_mode="r",
    ):
        self.file_path = file_path
        self.file_exists = False
        self.chunk_length = chunk_length
        self.open_file_mode = open_file_mode
        if not isfile(file_path):
            response_status = "404 Not Found"
        else:
            if mime_type is None:
                guessed_type = mimetypes.guess_type(file_path)
                mime_type = guessed_type[0] or fallback_mime_type
            if headers:
                headers["Content-type"] = "%s; charset=utf8" % (mime_type,)
            else:
                headers = {"Content-type": "%s; charset=utf8" % (mime_type,)}
            self.file_exists = True
        super().__init__("file:" + file_path, headers, response_status, cookie)

    def __call__(self):
        if self.file_exists is False:
            return
        file_handler = None
        try:
            file_handler = open(self.file_path, self.open_file_mode)
            while True:
                chunk = file_handler.read(self.chunk_length)
                if chunk:
                    yield chunk
                else:
                    return

        finally:
            if file_handler:
                file_handler.close()
